import re
import yaml
import argparse
import sys

def process_file(input_file, output_file, config):
    """处理输入文件，根据配置规则生成格式化的输出文件"""
    # 获取正则表达式配置
    chapter_pattern = config.get('chapter_pattern')
    section_pattern = config.get('section_pattern')
    
    with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
        for line in infile:
            # 检查是否为空行，如果是空行则跳过
            if not line.strip():
                continue
                
            # 去掉行首的空格和行尾的换行符
            line = line.lstrip().rstrip('\n')
            
            # 处理 "第X章" 和标题内容之间的空格
            line = re.sub(chapter_pattern, r'\1 \3', line)
            
            # 处理章节编号和章节名称之间的空格或制表符
            line = re.sub(section_pattern, r'\1 \3\4', line)

            # 处理一些特殊规则
            indent_config = config.get('indent_config', {})
            for pattern, setting in indent_config.items():
                if isinstance(setting, dict):
                    action = setting['action']
                    if action == 'insert_tab_before_last_digit' and re.search(pattern, line):
                        # 查找最后一个数字的位置
                        last_digit_index = len(line) - 1
                        while last_digit_index >= 0 and line[last_digit_index].isdigit():
                            last_digit_index -= 1
                        last_digit_index += 1
                        
                        # 在最后一个数字前插入制表符（如果还没有制表符）
                        if last_digit_index > 0 and line[last_digit_index - 1] != '\t':
                            line = line[:last_digit_index] + '\t' + line[last_digit_index:]
                            
                    elif action == 'append_tab_and_na' and re.search(pattern, line):
                        line = line + '\tNA'
                        
                    elif action == 'replace_spaces_with_tab' and re.search(pattern, line):
                        line = re.sub(pattern, r'\1\t\2', line)
                        
                elif re.match(pattern, line):
                    # 根据配置的缩进级别添加制表符
                    line = '\t' * setting + line

            # 写入输出文件
            outfile.write(line + '\n')

def load_config(config_file):
    """加载配置文件"""
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    except FileNotFoundError:
        print(f"错误：找不到配置文件 '{config_file}'")
        sys.exit(1)
    except Exception as e:
        print(f"错误：读取配置文件时发生异常: {e}")
        sys.exit(1)

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='处理书籍目录标记，生成格式化的目录文件')
    parser.add_argument('-i', '--input', default='book_mark_in.txt', help='输入文件路径（默认：book_mark_in.txt）')
    parser.add_argument('-o', '--output', default='book_mark_out.txt', help='输出文件路径（默认：book_mark_out.txt）')
    parser.add_argument('-c', '--config', default='re_book_mark.yml', help='配置文件路径（默认：re_book_mark.yml）')
    
    args = parser.parse_args()
    
    # 读取配置文件
    config = load_config(args.config)
    
    try:
        process_file(args.input, args.output, config)
        print(f"处理完成！结果已保存到 {args.output}")
    except FileNotFoundError:
        print(f"错误：找不到输入文件 '{args.input}'")
        sys.exit(1)
    except Exception as e:
        print(f"错误：处理文件时发生异常: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()